package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author NierMood
 * @version 1.0
 * @description
 * @date 2023/11/14 11:48
 */
@Slf4j
@RestController
@RequestMapping("/oldcommon")
public class  OldCommonController {
    @Value("G:/bookImg/")
    private String bookImg;

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        log.info(file.toString());
        String originalFilename = file.getOriginalFilename(); // 原始文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

//         使用uuid
        String filename = UUID.randomUUID().toString() + suffix;
//     创建一个目录对象
        File dir = new File(bookImg);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(bookImg, filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  AjaxResult.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception{
        System.out.println("测试"+name);
        FileInputStream fileInputStream = new FileInputStream(bookImg + name);
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];

        while((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }

        outputStream.close();
        fileInputStream.close();
    }
}
